import isEmpty from 'loadsh/isEmpty'
import { GetInfoPicture, GetPreviewImage, GetProcureApplicationInfo, PostDeleteData, PostInfoPicture, PostProcureApplicationInfo } from '/constData/requestFun/_httpRequest';
import { GetPurchaseRequest, GetPurchaseRequestById, PostPurchaseRequest, PurchaseRequestDeleteData } from '/constData/requestFun/_teseRequest';
import { POLICIES } from '/constData/_';
import compact from 'loadsh/compact'
import { CORPID, SPACEID } from '/constData/requestFun/_globalData';
Page({
  data: {
    approve: [],
    options: [
      { value: '办公用品', label: '办公用品' },
      { value: '日常用品', label: '日常用品' },
      { value: '材料用品', label: '材料用品' },
      { value: '设备用品', label: '设备用品' },
      { value: '其他用品', label: '其他用品' },
    ],
    Moneyoptions: [
      { value: '预计金额', label: '预计金额' },
      { value: '确认金额', label: '确认金额' },
    ],
    item: 1,
    min: null,
    max: new Date('2033/12/02'),
    defaultDate: new Date(),
    purchaseinfo: {
      CorpId: '',
      ProcureProject: '',//采购项目说明
      ProcurType: '办公用品',//采购类型
      ExplanatExpenditure: '', //经费支出说明
      PurchaseDate: '',//预计采购日期
      AmountType: '',//金额类型
      TotalAmount: '',//总金额
      Notes: '',//备注
      Picture: '', //图片
      Annex: '[]', //附件
      ProcureMethod: '',//采购方式,
      largeAmount: ''
    },
    ReceiveData: [],
    displaydata: [],
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    PurchaseRequestDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },
  handleOk1(date, format, e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        PurchaseDate: date
      },
    })
  },
  onProcureProjectChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        ProcureProject: e
      }
    })
  },
  onExplanatExpenditureChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        ExplanatExpenditure: e
      }
    })
  },
  onTotalAmountChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        TotalAmount: e,
        largeAmount: intToChinese(e)
      }
      , approve: POLICIES.PURCHAS_POLICIES(e)
    })
  },
  onNotesChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        Notes: e
      }
    })
  },
  onProcureMethodChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        ProcureMethod: e
      }
    })
  },
  handleChange(value) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        ProcurType: value
      }
    });
  },
  handleMoneyTypeChange(value) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        AmountType: value
      }
    });
  },

  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        GetPurchaseRequest((res) => {
          const cacheData = res.data.map(it => {
            console.log('it', it);
            if (it.item1.corpId === storage.data.result.userid) {
              it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
              return it
            }
          })
          this.setData({
            purchaseinfo: {
              ...this.data.purchaseinfo,
              CorpId: storage.data.result.userid
            },
            ReceiveData: compact(cacheData).reverse()
          })
        })
      }
    })
  },
  // 上传数据
  onSubmit(e) {
    PostPurchaseRequest(JSON.stringify(this.data.purchaseinfo),
      (res) => {
        my.alert({
          title: '提交成功',
        });
        GetPurchaseRequestById(res.data, (res) => {
          this.setData({
            ReceiveData: compact([...this.data.ReceiveData, res.data].map(it => {
              if (it.item1.corpId === this.data.purchaseinfo.CorpId) {
                it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
                return it
              }
            })).reverse()
          })
        })
        this.setData({
          purchaseinfo: {
            ...this.data.purchaseinfo,
            ProcureProject: '',//采购项目说明
            ProcurType: '办公用品',//采购类型
            ExplanatExpenditure: '', //经费支出说明
            PurchaseDate: '',//预计采购日期
            TotalAmount: '',//总金额
            Notes: '',//备注
            Picture: '', //图片
            Annex: '[]', //附件
            ProcureMethod: '',//采购方式,
            largeAmount: ''
          }
        })
      },
      (err) => {
        my.alert({
          title: '提交成功1',
        });
      })
  },
  //上传图片
  onUpload() {
    let imageAnnex = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      types: ['photo'],
      success: (res) => {
        const srcAnnex = this.data.purchaseinfo.Annex
        imageAnnex = res.data
        imageAnnex.push(...JSON.parse(srcAnnex))
        this.setData({
          displaydata: imageAnnex,
          purchaseinfo: {
            ...this.data.purchaseinfo,
            Annex: JSON.stringify(imageAnnex)
          }
        })
      },
      fail: () => { },
      complete: () => { },
    });
  },
  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },

  // //图片下载函数
  // DownImg(e) {
  //   const imgNames = e.currentTarget.dataset.picture.split(',');
  //   if (isEmpty(e.currentTarget.dataset.picture)) {
  //     my.alert({ content: '无附件图片！' })
  //   } else {
  //     Promise.all(imgNames.map(imgName =>
  //       new Promise((resolve) => {
  //         GetInfoPicture(imgName, (res) => {
  //           resolve(res.filePath)
  //         })
  //       })
  //     )).then(res => {
  //       GetPreviewImage(res)
  //     })
  //   }
  // },

});

function intToChinese(money) {
  //汉字的数字
  var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  //基本单位
  var cnIntRadice = ['', '拾', '佰', '仟'];
  //对应整数部分扩展单位
  var cnIntUnits = ['', '万', '亿', '兆'];
  //对应小数部分单位
  var cnDecUnits = ['角', '分', '毫', '厘'];
  //整数金额时后面跟的字符
  var cnInteger = '整';
  //整型完以后的单位
  var cnIntLast = '元';
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  //金额整数部分
  var integerNum;
  //金额小数部分
  var decimalNum;
  //输出的中文金额字符串
  var chineseStr = '';
  //分离金额后用的数组，预定义
  var parts;
  if (money === '') { //不能用==
    return '';
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return '';
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //转换为字符串
  money = money.toString();
  if (money.indexOf('.') == -1) {
    integerNum = money;
    decimalNum = '';
  } else {
    parts = money.split('.');
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == '0') {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != '') {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == '') {
    chineseStr += cnInteger;
  }
  return chineseStr;
}